package com.dc.dbus.transport.netty.client;

import java.util.concurrent.atomic.AtomicInteger;

import com.dc.dbus.transport.netty.client.exception.CantFindActiveServiceException;
import com.dc.dbus.transport.netty.client.node.NodeLink;

public class ServiceRegion {
	
	final String serviceName;
	
	final String router;
	
	final AtomicInteger index = new AtomicInteger(0);
	
	final NodeLink[] nodeLinks;
	
	public ServiceRegion(String serviceName, String router, NodeLink[] nodeLinks) {
		super();
		this.serviceName = serviceName;
		this.router = router;
		this.nodeLinks = nodeLinks;
	}

	public void writeAndFlush(String router, Object obj, int invokeSessionTimeout) {
		
		NodeLink[] nodeLinks = this.nodeLinks;
		if (nodeLinks.length == 0) {
			throw new CantFindActiveServiceException("not active server for service:" + serviceName + ", router:" + router);
		}

		if (nodeLinks.length == 1) {
			if (!nodeLinks[0].writeAndFlush(obj, invokeSessionTimeout)) {
				throw new CantFindActiveServiceException("not active server(2) for service:" + serviceName + ", router:" + router);
			}
		} else {

			int next = index.getAndIncrement() % nodeLinks.length;
			NodeLink n = nodeLinks[next];
			if (n.writeAndFlush(obj, invokeSessionTimeout)) {
				return;
			} else {
				// 发送失败，尝试遍历所有node发送
				for (int i=1; i<nodeLinks.length; i++) {
					next++;
					if (next >= nodeLinks.length) {
						next = 0;
					}
					if (nodeLinks[next].writeAndFlush(obj, invokeSessionTimeout)) {
						return;
					}
				}
				throw new CantFindActiveServiceException("not active server(3) for service:" + serviceName + ", router:" + router);
			}
		}
		
	}
}